<?php
header('Content-Type: image/png');
$pfilielist = isset($_GET['file']) ? $_GET['file'] : '';
$pfilielist = DIRECTORY_SEPARATOR.$pfilielist;
// _DSC7005.jpg IMG_0143.JPG IMG_0027.JPG

$srcinfo = exif_read_data($pfilielist,NULL,true,true);//得到原图大小
//var_dump($srcinfo);
//die;
/**
*25年来看考虑不周，PNG图片第7行就没法兜底了，15 16行数字改一下位置就不对了。
*/

$infothumb = [];
$infothumb['width'] = 250;
$infothumb['height'] = 150;
$newimg = imagecreatetruecolor($infothumb['width'],$infothumb['height']);
imagealphablending($newimg, true);
imagesavealpha($newimg, true);
$transcolour = imagecolorallocatealpha($newimg, 0, 0, 0, 127);
imagefill($newimg, 0, 0, $transcolour);
imagecolortransparent($newimg, imagecolorallocate($newimg,0,0,0));


if(isset($srcinfo['COMPUTED']) AND isset($srcinfo['THUMBNAIL']) AND isset($srcinfo['THUMBNAIL']['THUMBNAIL'])){//能够取到缩略图流
  $liteimghig = isset($srcinfo['COMPUTED']['Thumbnail.Height']) ? $srcinfo['COMPUTED']['Thumbnail.Height'] :$infothumb['height'];
  $liteimgwdh = isset($srcinfo['COMPUTED']['Thumbnail.Width']) ? $srcinfo['COMPUTED']['Thumbnail.Width'] : $infothumb['width'];
  $srcimg = imagecreatefromstring($srcinfo['THUMBNAIL']['THUMBNAIL']);
  
  if($liteimghig <= $infothumb['height'] && $liteimgwdh <= $infothumb['width']){//只算比目标图片小
	  //算居中
	  $nleft = bcsub($infothumb['width'],$liteimgwdh,0);
	  $nleft = bcdiv($nleft,2,0);
	  
	  $ntop = bcsub($infothumb['height'],$liteimghig,0);
	  $ntop = bcdiv($ntop,2,0);
  }else if($liteimgwdh <= $infothumb['height'] && $liteimghig <= $infothumb['width']){//可能竖的缩略图
	  $ntop = bcsub($infothumb['height'],$liteimghig,0);
	  //$ntop = bcdiv($ntop,2,1);
	  $nleft = bcsub($infothumb['width'],$liteimgwdh,0);
	  $nleft = bcdiv($nleft,2,0);
  }
  
  imagecopymerge($newimg, $srcimg, $nleft, $ntop, 0, 0,  $liteimgwdh,$liteimghig,100);
  imagedestroy($srcimg);
  //var_dump($srcinfo['THUMBNAIL']['THUMBNAIL']);
}else if(isset($srcinfo['COMPUTED'])){
  $liteimghig = isset($srcinfo['COMPUTED']['Height']) ? $srcinfo['COMPUTED']['Height'] : $infothumb['height'];
  $liteimgwdh = isset($srcinfo['COMPUTED']['Width']) ? $srcinfo['COMPUTED']['Width'] : $infothumb['width'];
  $srcimg = file_get_contents($pfilielist);
  $srcimg = imagecreatefromstring($srcimg);
  $ntop = 0;
  $nleft = 0;
  if($liteimgwdh < $liteimghig){
	$pfilielist = $infothumb['height'];
	$infothumb['height'] = $infothumb['width'];
	$infothumb['width'] = $pfilielist;
	unset($pfilielist);
	$nleft = bcdiv($infothumb['width'], 3,0);
	$ntop = -bcdiv($infothumb['height'] , 5,0);
  }
  
  ImageCopyResampled($newimg,$srcimg,$nleft,$ntop,0,0,$infothumb['width'],$infothumb['height'],$liteimgwdh,$liteimghig);
  imagedestroy($srcimg);
}
imagepng($newimg);
imagedestroy($newimg);